package com.topsoft.common;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.sql.Date;
import java.text.DecimalFormat;
import java.util.*;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

@Slf4j
public class MiscHelper {
    public static boolean isDebug=false;
    static {
        isDebug=log.isDebugEnabled();
    }

    //将字符按照指定的 分割符切分成数据ArrayList
    public static JSONObject urlParameter2Map(String string){
        if (string == null || string.equals("")) return null;

        ArrayList<String> arrayList = new ArrayList<String>();
        arrayList = string2Array(string, "&");

        JSONObject jsonObject = new JSONObject(true);
        for (String str : arrayList){
            String[] pos = str.split("=");
            jsonObject.put(pos[0],pos.length==1?"":pos[1]);
        }
        return jsonObject;
    }

    public static String fillStr(Object as_str, int ai_len, String as_fill_str) {
        for (int i = 0; i < ai_len; i++) {
            if (as_str.toString().length() < ai_len) as_str = as_fill_str + as_str;
        }

        return as_str.toString();
    }

    //将字符按照指定的 分割符切分成数据ArrayList
    public static ArrayList<String> string2Array(String string, String split){
        ArrayList<String> arrayList = new ArrayList<String>();
        if (string==null) {
            return arrayList;
        }
        StringTokenizer st=new StringTokenizer(string,split);
        while(st.hasMoreTokens()) {
            String _value=st.nextToken().trim();
            if (!MiscHelper.isNull(_value) && !arrayList.contains(_value)) {
                arrayList.add(_value);
            }
        }

        return arrayList;
    }
    public static Set<String> string2Set(String string, String split){
        Set<String> set = new HashSet<String>();
        if (MiscHelper.isNull(string)) {
            return set;
        }
        string=string.replace("，",",");
        StringTokenizer st=new StringTokenizer(string,split);
        while(st.hasMoreTokens()) {
            String _value=st.nextToken().trim();
            if (!MiscHelper.isNull(_value)) {
                set.add(_value);
            }
        }

        return set;
    }

    public static boolean isNull(Object _str) {
        if (_str ==null) return true;

        if(_str == "" || _str.equals("") || _str.equals("null"))
            return true;
        else
            return false;
    }

//    public static String getDateTime() {
//        return MiscHelper.getDate().toString() + " " + MiscHelper.getTime();
//    }
//    public static String getDateTime2() {
//        return MiscHelper.getDate().toString() + " " + MiscHelper.getTime2();
//    }
//    public static Date getDate() {
//        Calendar calendar = Calendar.getInstance();
//
//        return new Date(new GregorianCalendar(calendar.get(Calendar.YEAR),
//                calendar.get(Calendar.MONTH),
//                calendar.get(Calendar.DAY_OF_MONTH)).getTimeInMillis());
//    }
//    public static String getTime() {
//        Calendar calendar = Calendar.getInstance();
//        DecimalFormat df = new DecimalFormat("00");
//        return df.format(calendar.get(Calendar.HOUR_OF_DAY))+ ":"
//                + df.format(calendar.get(Calendar.MINUTE))+ ":"
//                + df.format(calendar.get(Calendar.SECOND))+ " "
//                + new DecimalFormat("000").format(calendar.get(Calendar.MILLISECOND));
//    }
//    public static String getTime2() {
//        Calendar calendar = Calendar.getInstance();
//        DecimalFormat df = new DecimalFormat("00");
//        return df.format(calendar.get(Calendar.HOUR_OF_DAY))+ ":"
//                + df.format(calendar.get(Calendar.MINUTE))+ ":"
//                + df.format(calendar.get(Calendar.SECOND));
//    }

    public static String fillStr(String as_str, int ai_len,  String as_fill_str){
        for (int i=0; i<ai_len; i++){
            if (as_str.length() < ai_len) as_str = as_fill_str+as_str;
        }

        return as_str;
    }

    /** 字符串压缩为字节数组*/
    public static byte[] gzip2byte(String str) {
        return gzip2byte(str,null);
    }
    public static byte[] gzip2byte(String str,String encoding){
        if (str == null || str.length() == 0) {
            return null;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        GZIPOutputStream gzip=null;
        try {
            gzip = new GZIPOutputStream(out);
            if(encoding==null)  gzip.write(str.getBytes());
            else gzip.write(str.getBytes(encoding));
            gzip.close();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (gzip != null)try { gzip.close(); } catch (IOException e) { }
            if (out != null)   try { out.close();    } catch (IOException e) { }
        }
        return out.toByteArray();
    }

    /** 压缩为字符串 */
    public static String gzip2String(String primStr) {
        return  Base64.getEncoder().encodeToString(gzip2byte(primStr));
    }
    public static String gzip2String(String primStr,String encoding) {
        return  Base64.getEncoder().encodeToString(gzip2byte(primStr,encoding));
    }
    /* 字节数组解压缩后返回字符串     */
    public static String gunzip(byte[] b) {
        return gunzip(b,null);
    }
    public static String gunzip(byte[] b,String charsetName){
        if (b == null || b.length == 0) {
            return null;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ByteArrayInputStream in = new ByteArrayInputStream(b);
        GZIPInputStream gunzip=null;
        try {
            gunzip = new GZIPInputStream(in);
            byte[] buffer = new byte[256];
            int n;
            while ((n = gunzip.read(buffer)) >= 0) {
                out.write(buffer, 0, n);
            }

            if (charsetName==null || charsetName.equals("")) {
                return out.toString();
            }else{
                return out.toString(charsetName);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (gunzip != null)try { gunzip.close(); } catch (IOException e) { }
            if (in != null)    try { in.close();     } catch (IOException e) { }
            if (out != null)   try { out.close();    } catch (IOException e) { }
        }
        return null;
    }

    /** 解压 */
    public static String gunzip(String compressedStr) {
        return gunzip(compressedStr,null);
    }
    /** 解压 */
    public static String gunzip(String compressedStr,String charsetName) {
        if (compressedStr == null) {
            return null;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ByteArrayInputStream in = null;
        GZIPInputStream ginzip = null;
        byte[] compressed = null;
        String decompressed = null;
        try {
            compressed =Base64.getDecoder().decode(compressedStr);
            in = new ByteArrayInputStream(compressed);
            ginzip = new GZIPInputStream(in);

            byte[] buffer = new byte[1024];
            int offset = -1;
            while ((offset = ginzip.read(buffer)) != -1) {
                out.write(buffer, 0, offset);
            }
            if (charsetName==null || charsetName.equals("")){
                decompressed = out.toString();
            }else{
                decompressed = out.toString(charsetName);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ginzip != null)try { ginzip.close(); } catch (IOException e) { }
            if (in != null)    try { in.close();     } catch (IOException e) { }
            if (out != null)   try { out.close();    } catch (IOException e) { }
        }
        return decompressed;
    }

    public static void main(String[] args) throws Exception {
        String str="H4sIAAAAAAAAAKtWyi1OV7JSOvJ412ElHaX4+MLS1NJUoEBJanGJhVItAH7gH5ogAAAA";
        //System.out.println(gunzip(str,"UTF-8"));
    }

//    /**
//     * 使用zip进行压缩
//     * @param str 压缩前的文本
//     * @return 返回压缩后的文本
//     */
//    public static final String zip(String str) {
//        if (str == null)
//            return null;
//        byte[] compressed;
//        ByteArrayOutputStream out = null;
//        ZipOutputStream zout = null;
//        String compressedStr = null;
//        try {
//            out = new ByteArrayOutputStream();
//            zout = new ZipOutputStream(out);
//            zout.putNextEntry(new ZipEntry("0"));
//            zout.write(str.getBytes());
//            zout.closeEntry();
//            compressed = out.toByteArray();
//            compressedStr = new sun.misc.BASE64Encoder().encodeBuffer(compressed);
//        } catch (IOException e) {
//            compressed = null;
//        } finally {
//            if (zout != null) {
//                try {
//                    zout.close();
//                } catch (IOException e) {
//                }
//            }
//            if (out != null) {
//                try {
//                    out.close();
//                } catch (IOException e) {
//                }
//            }
//        }
//        return compressedStr;
//    }
}
